from django.http import JsonResponse
import graphene
from starlette_graphql import GraphQLApp
from fastapi import APIRouter
from app.db.db_auth import DBAuth
from app.utils.password import hash_password

router = APIRouter(prefix="/graphql",
                   tags=["graphql V1"],)

db_dict = dict()

# 定义一个简单的 User 类型
class User(graphene.ObjectType):
    # id = graphene.Int()
    username = graphene.String()
    # email = graphene.String()
    hashed_password = graphene.String()

# 定义查询类型
class Query(graphene.ObjectType):
    user = graphene.Field(User, username=graphene.String(required=True))  # 控制入参

    def resolve_user(self, info, username):
        db_user: DBAuth = db_dict["User"]
        users = db_user.get_user(username)

        # 这里可以从数据库或其他数据源获取用户数据
        # users = [
        #     User(id=1, name="Alice", email="alice@example.com"),
        #     User(id=2, name="Bob", email="bob@example.com"),
        # ]
        # 根据 ID 查找用户
        for user in users:
            if user.username == username:
                return user
        return None  # 如果没有找到用户


# 创建 schema
schema_query = graphene.Schema(query=Query)

# GET 请求
router.add_route("/graphql/get_user", GraphQLApp(schema=schema_query))


# 定义变更类型--这个graphene.Mutation类型决定使用GET还是POST请求
class CreateUser(graphene.Mutation):
    class Arguments:
        username = graphene.String(required=True)
        password = graphene.String(required=True)

    user = graphene.Field(User)

    def mutate(self, info, username, password):
        # user_id = len(fake_users_db) + 1  # 简单的 ID 生成
        new_user = User(username=username, hashed_password=hash_password(password))
        db_user: DBAuth = db_dict["User"]
        users = db_user.get_user_by_username(username)
        if users:
            raise Exception("用户已存在")
        db_user.create_user(username, hashed_password=hash_password(password))

        return JsonResponse(data={"data": {"user": new_user}})

# # 定义查询类型
# class Query(graphene.ObjectType):
#     users = graphene.List(User)

#     def resolve_users(self, info):
#         return fake_users_db

# 定义根类型
class Mutation(graphene.ObjectType):
    create_user = CreateUser.Field()

# 创建 schema
schema_mutation = graphene.Schema(query=Query, mutation=Mutation)

# POST 请求
router.add_route("/graphql/post_user", GraphQLApp(schema=schema_mutation))